package com.lz.gmall.rabbit.config;

import com.lz.gmall.rabbit.constant.RabbitConstant;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 郭运龙
 */
@Configuration
public class OrderMqConfiguration {

    /**
     * 声明业务交换机同时也是死信交换机
     * @return
     */
    @Bean
    public Exchange orderExchange(){
         return ExchangeBuilder.topicExchange(RabbitConstant.ORDER_EXCHANGE_NAME).durable(true).build();
    }

    /**
     * 声明业务队列的ttl，超时进入死信队列
     * @return
     */
    @Bean
    public Queue orderQueue(){
        return QueueBuilder.durable(RabbitConstant.ORDER_QUEUE_NAME)
                .deadLetterExchange(RabbitConstant.ORDER_EXCHANGE_NAME)
                .deadLetterRoutingKey(RabbitConstant.DELAY_QUEUE_ROUTING_KEY_NAME)
                .ttl(RabbitConstant.ORDER_QUEUE_TTL)
                .build();
    }

    /**
     * 绑定关系
     * @param orderExchange 业务交换机
     * @param orderQueue    业务超时进入死信的队列
     * @return
     */
    @Bean
    public Binding orderBinding(Exchange orderExchange,Queue orderQueue){
        return BindingBuilder.bind(orderQueue).to(orderExchange)
                .with(RabbitConstant.ORDER_QUEUE_ROUTING_KEY_NAME).noargs();
    }

    /**
     * 声明死信队列
     * @return
     */
    @Bean
    public Queue delayQueue(){
        return QueueBuilder.durable(RabbitConstant.DELAY_QUEUE_NAME).build();
    }

    /**
     * 绑定关系
     * @param orderExchange 死信交换机（也是业务交换机）
     * @param delayQueue  死信队列
     * @return
     */
    @Bean
    public Binding delayBinding(Exchange orderExchange,Queue delayQueue){
        return BindingBuilder.bind(delayQueue).to(orderExchange)
                .with(RabbitConstant.DELAY_QUEUE_ROUTING_KEY_NAME)
                .noargs();
    }

    @Bean
    public Queue payedQueue(){
        return QueueBuilder.durable(RabbitConstant.PAYED_QUEUE_NAME).build();
    }

    @Bean
    public Binding payedBinding(){
        return BindingBuilder.bind(payedQueue())
                .to(orderExchange())
                .with(RabbitConstant.PAYED_QUEUE_ROUTING_KEY_NAME)
                .noargs();
    }

    /**
     * 库存减完发送消息到order，更改订单状态（待发货）
     * 发送到该交换机
     * @return
     */
    @Bean
    public Exchange wareStockExchange(){
        return ExchangeBuilder.topicExchange(RabbitConstant.EXCHANGE_DIRECT_WARE_ORDER).durable(true).build();
    }

    /**
     * 库存减完发送消息到order，更改订单状态（待发货）
     * 发送到该队列
     * @return
     */
    @Bean
    public Queue wareStockQueue(){
        return QueueBuilder.durable(RabbitConstant.QUEUE_WARE_ORDER).build();
    }

    /**
     * 绑定上述交换机和队列
     * @return
     */
    @Bean
    public Binding wareStockBinding(){
        return BindingBuilder.bind(wareStockQueue()).to(wareStockExchange()).with(RabbitConstant.ROUTING_WARE_ORDER).noargs();
    }

}
